package com.congee02.exit;

import java.util.Date;

/**
 * @author congee02
 * @date 2/1/2023 11:01 AM
 */
public class ThreadInterruptTest {

    public static void main(String[] args) throws InterruptedException {
        ThreadToBeInterrupted thread = new ThreadToBeInterrupted();
        thread.start();
        thread.setName("靓仔");
        thread.setPriority(Thread.MIN_PRIORITY);

        System.out.println("*****" + thread.getName() + ", 线程优先级 = " + thread.getPriority() + "*****");
        
        for (int i = 0 ; i < 5 ; i ++ ) {
            Thread.sleep(1 * 1000);
            System.out.println("Hi " + i);
        }
        
        // 触发 catch (InterruptedException e)，中断线程的休眠
        // 提前结束休眠
        thread.interrupt();
    }
    
    private static class ThreadToBeInterrupted extends Thread {
        @Override
        public void run() {
            while (true) {
                String name = Thread.currentThread().getName();
                System.out.println((name + " 正在学习 ..."));
                try {
                    System.out.println("线程\t" + name + "\t正在休眠\t" + new Date());
                    sleep(20 * 1000);
                } catch (InterruptedException e) {
                    System.out.println("线程\t" + name + "\t被中断\t" + new Date());
                }
            }
        }
    }
    
}
